import React, { Component } from "react";
import { Card, Form, Input, Cascader, Upload, Button } from "antd";
import LinkButton from "../../components/link-button";
import { ArrowLeftOutlined } from "@ant-design/icons";
import { reqCategorys } from "../../api/index";
import PicturesWall from "./pictures-wall";
import RichTextEditor from "./RichTextEditor";

const { Item } = Form;
const { TextArea } = Input;

export default class ProductAddUpdate extends Component {
  state = {
    options: [],
  };

  constructor(props) {
    super(props);
    this.pw = React.createRef();
    this.editor = React.createRef();
  }

  formRef = React.createRef();

  getCategorys = async (parentId) => {
    const result = await reqCategorys(parentId);
    console.log(9999, result);
    if (result.data.status === 0) {
      const categorys = result.data.data;
      //如果是一级分类列表
      if (parentId === "0") {
        this.initOptions(categorys);
      } else {
        return categorys; //返回二级列表
      }
    }
  };
  //debugger
  initOptions = async (categorys) => {
    //根据categorys数组生成options数组
    const options = categorys.map((c) => ({
      value: c.id,
      label: c.name,
      isLeaf: false,
    }));
    //如果是一个二级分类商品
    const { isUpdate, product } = this;
    const { pcategoryid } = product;
    if (isUpdate && pcategoryid !== "0") {
      //获取对应二级分类列表
      const subCategorys = await this.getCategorys(pcategoryid);
      //生成二级下拉列表
      const childOptions = subCategorys.map((c) => ({
        value: c.id,
        label: c.name,
        isLeaf: true,
      }));
      //关联到一级列表
      const targetOption = options.find(
        (option) => option.value === pcategoryid
      );
      targetOption.children = childOptions;
    }
    //更新状态
    this.setState({ options });
  };

  componentDidMount() {
    this.getCategorys("0");
  }

  componentWillMount() {
    //在reder之前执行
    //取出state
    const product = this.props.location.state;
    console.log("000000", product);
    this.isUpdate = !!product;
    this.product = product || {};
    console.log("111111", this.isUpdate);
  }

  onFinish = (value) => {
    const detail = this.editor.current.getDetail();
    console.log("0980", detail);
  };
  loadData = async (selectedOptions) => {
    const targetOption = selectedOptions[0];
    targetOption.loading = true;

    //根据选中的分类，请求获取二级分类列表
    const subCategorys = await this.getCategorys(targetOption.value);
    targetOption.loading = false;
    //有无二级分类
    if (subCategorys && subCategorys.length > 0) {
      const childOptions = subCategorys.map((c) => ({
        value: c.id,
        label: c.name,
        isLeaf: true,
      }));
      targetOption.children = childOptions;
    } else {
      targetOption.isLeaf = true;
    }

    this.setState({
      options: [...this.state.options],
    });
  };

  validatePrice = (rule, value, callback) => {
    if (value * 1 > 0) {
      callback();
    } else {
      callback("价格大于0");
    }
  };

  render() {
    //console.log(345, this.formRef);
    //defaultValue={product.name}

    const { isUpdate, product } = this;
    const { pcategoryid, categoryid } = product;
    //接收级联的分类ID数组
    const categoryIds = [];
    if (isUpdate) {
      //如果是一级
      if (pcategoryid === "0") {
        categoryIds.push(categoryid);
      } else {
        categoryIds.push(pcategoryid);
        categoryIds.push(categoryid);
      }
    }
    console.log("wxfhy13263627t", product.detail);
    const formItemLayout = {
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 8,
      },
    };
    const title = (
      <span>
        <LinkButton onClick={() => this.props.history.goBack()}>
          <ArrowLeftOutlined />
        </LinkButton>
        <span>{isUpdate ? "修改商品" : "添加商品"}</span>
      </span>
    );
    return (
      <Card title={title}>
        <Form {...formItemLayout} ref={this.formRef} onFinish={this.onFinish}>
          <Item
            label="商品名称"
            rules={[{ required: true, message: "必须输入" }]}
          >
            <Input placeholder="请输入商品名称" defaultValue={product.name} />
          </Item>
          <Item label="商品描述">
            <TextArea
              placeholder="请输入商品描述"
              autosize
              defaultValue={product.descp}
            />
          </Item>
          <Item
            label="商品价格"
            rules={[
              { required: true, message: "必须输入" },
              { validator: this.validatePrice },
            ]}
          >
            <Input
              type="number"
              placeholder="请输入商品价格"
              addonAfter="元"
              defaultValue={product.price}
            />
          </Item>
          <Item label="商品分类">
            <Cascader
              options={this.state.options}
              loadData={this.loadData}
              defaultValue={categoryIds}
            />
          </Item>
          <Item label="商品图片">
            <PicturesWall ref={this.pw} />
          </Item>
          <Item
            label="商品详情"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <RichTextEditor ref={this.editor} detail={product.detail} />
          </Item>
          <Item>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Item>
        </Form>
      </Card>
    );
  }
}
